package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import dao.BaseDao;
import dao.CheckDao;
import entity.User;

public class ICheckDao extends BaseDao implements CheckDao{
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
	@Override
	public boolean checklogin(User u) {//登陆检测
		boolean flag = false;
		try {
			String sql ="select * from shopping_user where 1=1 ";
			if (u.getUsername()!=""&&u.getUsername()!=null) {
				sql+="and username = '"+u.getUsername()+"' ";
			}
			if (u.getPassword()!=""&&u.getPassword()!=null) {
				sql+="and password = '"+u.getPassword()+"' ";
			}
			con = super.getConnection();
			ps = con.prepareStatement(sql);
			rs=ps.executeQuery();
			while(rs.next()){
				flag = true;
			}
			rs.close();
			ps.close();
			con.close();
			return flag;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
	@Override
	public boolean adduser(User u) {//添加用户
		try {
			String sql ="insert into shopping_user values(shopping_userseq.nextval,?,?,?,null,?,?,?,null,?,null,null)";
			con = super.getConnection();
			ps = con.prepareStatement(sql);
			ps.setString(1, u.getUsername());
			ps.setString(2, u.getPassword());
			ps.setString(3, u.getName());
			ps.setString(4, u.getEmail());
			ps.setString(5, u.getSex());
			ps.setString(6, u.getBorn());
			ps.setString(7, u.getPower());
			ps.execute();
			
			ps.close();
			con.close();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
	@Override
	public User FindUser(String username) {//根据 用户名找用户
		User u = new User();
		try {
		String sql ="select * from shopping_user where username=?";
		con = super.getConnection();
		ps = con.prepareStatement(sql);
		ps.setString(1, username);
		rs=ps.executeQuery();
		while(rs.next()){
			u.setUsername(rs.getString(2));
			u.setName(rs.getString(4));
			u.setAddress(rs.getString(11));
			u.setTel(rs.getString(12));
		}
		ps.close();
		con.close();
		
		return u!=null?u:null;
	} catch (SQLException e) {
		e.printStackTrace();
	}
		
		return null;
	}
	@Override
	public boolean UpUser(String username, String address, String tel) {//根据用户名修改地址和电话
		try {
			String sql ="update shopping_user set address=?,tel=? where username=?";
			con = super.getConnection();
			ps = con.prepareStatement(sql);
			ps.setString(1, address);
			ps.setString(2,tel);
			ps.setString(3, username);
			ps.execute();
			
			ps.close();
			con.close();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return false;
	}

}
